package com.roujuan.controller;

import com.alibaba.fastjson.JSONObject;
import com.roujuan.entity.*;
import com.roujuan.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("/department/list")
    @ResponseBody
    public String getDepartmentList(){
        List<Department> departmentsList =  departmentService.getDepartmentList();
        Integer total = departmentsList.size();
        DepartmentList items = new DepartmentList(total,departmentsList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 20000);
        jsonObject.put("data",items);
        return JSONObject.toJSONString(jsonObject);
    }

    @RequestMapping("/department/queryList")
    @ResponseBody
    public String getDepartmentListByQuery(DepartmentQuery departmentQuery){
        List<Department> departmentsList =  departmentService.getDepartmentListByQuery(departmentQuery);
        Integer total = departmentService.getDepartmentListTotal(departmentQuery);
        DepartmentList items = new DepartmentList(total,departmentsList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 20000);
        jsonObject.put("data",items);
        return JSONObject.toJSONString(jsonObject);
    }

    @RequestMapping("/department/delete")
    @ResponseBody
    public String deleteDepartmentById(Integer id){
        Integer result = departmentService.deleteDepartment(id);
        if(result == 1){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 20000);
            jsonObject.put("data","success");
            return JSONObject.toJSONString(jsonObject);
        }
       return "failed";
    }

    @RequestMapping("/department/create")
    @ResponseBody
    public String insertDepartmentById(Department department){
        Integer result = departmentService.insertDepartment(department);
        if(result>0){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 20000);
            jsonObject.put("data",department.getId());
            return JSONObject.toJSONString(jsonObject);
        }
        return "failed";
    }

    @RequestMapping("/department/update")
    @ResponseBody
    public String updateDepartment(Department department){
        Integer result = departmentService.updateDepartment(department);
        if(result==1){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 20000);
            jsonObject.put("data","success");
            return JSONObject.toJSONString(jsonObject);
        }
        return "failed";
    }
}
